from flask import jsonify, render_template, request
from app.routes import main_bp
from app.utils.file_handler import FileHandler
from app.utils.ip_checker import IPChecker
from app.config import config
from datetime import datetime

file_handler = FileHandler(
    base_path=config.DATA_DIR,
    max_records=config.MAX_RECORDS
)
ip_checker = IPChecker()

@main_bp.route('/')
def home():
    return render_template('index.html')

@main_bp.route('/api/get_ip', methods=['POST'])
def get_ip():
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '数据不能为空'}), 400
            
        # 验证数据格式
        if not isinstance(data.get('ipv4', []), list) or not isinstance(data.get('ipv6', []), list):
            return jsonify({'error': '无效的IP数据格式'}), 400
        
        # 过滤并只保留公网IP
        public_ipv4s, public_ipv6s = IPChecker.filter_public_ips(
            data.get('ipv4', []),
            data.get('ipv6', [])
        )
        
        # 保存IP数据
        ip_data = {
            'ipv4': public_ipv4s,
            'ipv6': public_ipv6s,
            'timestamp': datetime.now().isoformat()
        }
        
        # 只有当有公网IP时才保存
        if public_ipv4s or public_ipv6s:
            success = file_handler.append_ip_data(ip_data)
            
            if success:
                return jsonify({
                    "status": "success",
                    "message": "公网IP地址已记录",
                    "data": ip_data
                })
            else:
                return jsonify({'error': '保存失败'}), 500
        else:
            return jsonify({
                "status": "warning",
                "message": "未发现可用的公网IP地址",
                "data": ip_data
            }), 200
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@main_bp.route('/api/get_latest_ips', methods=['GET'])
def get_latest_ips():
    """获取最新的IP地址列表"""
    try:
        data = file_handler.read_ip_data()
        if not data:
            return jsonify({
                'ipv4': [],
                'ipv6': [],
                'timestamp': ''
            })
            
        # 获取最新的记录
        latest = data[-1] if data else {"ipv4": [], "ipv6": [], "timestamp": ""}
        
        return jsonify(latest)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500